import * as echarts from '../../ec-canvas/echarts';
const app = getApp()
const utils = require('../../utils/util.js')
let chartInstance;
function setOption(chart, options) {
  const option = {
    title: {
      left: 24,
      text: '水位监控图',
      textStyle: {
        color: '#333333',
        fontSize: 14
      },
      subtext: '水位（单位cm）',
      subtextStyle: {
        color: '#666666',
        fontSize: 11
      }
    },
    color: ["#3366ff"],
    legend: {
      right: 24,
      data: options.legend
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        return (params[0].data[0] + '\n' +"水位:" 
                +  params[0].data[1] + "cm");
      }
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      axisTick: {
        show: false
      }
    },
    yAxis: {
      show: false,
      boundaryGap: [0, '100%'],
    },
    series: options.series, 
    dataZoom: [
      {
        type: 'slider',
        show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
        start: 0,
        end: 45,
        // handleSize: 88  该属性是缩放手柄的宽度
      },
      {
        type: 'inside',
        start: 0,
        end: 45
      }
    ]
  };
  chart.setOption(option);
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    skin: '',
    no: '',  // 设备号
    barnName: '',
    zoneName: '',
    devName: '',
    deviceId : 0,
    beginTime: '', // 开始日期
    endTime: '', // 结束日期
    dataLevelList : []
  },

  handleBeginTimeChange(e) {
    this.setData({
      beginTime: e.detail
    })

    this.handleTimeChange()
  },

  handleEndTimeChange(e) {
    this.setData({
      endTime: e.detail
    })

    this.handleTimeChange()
  },

  handleTimeChange() {
    let that = this;
    const { beginTime, endTime } = this.data
    if (beginTime && endTime) {
      let queryParams = {
        "deviceId" : this.data.deviceId,
        "beginTime" : beginTime + " 00:00:00",
        "endTime" : endTime + " 23:59:59"
      };
      utils.promiseGet('/wx/device/waterchannel/getWaterData', queryParams).then(function(res){
        let shuiweiData = {
          name : "水位",
          data: [],
          type: 'line',
          areaStyle: {}
        };
        if (res.code == 200 && res.data) {
          if (res.data.list.length > 0) {
            var shuiweiArr = [];
            for (var i = 0; i < res.data.list.length; i++) {
              var shuiItem = new Array(res.data.list[i].createTime, res.data.list[i].level);
              shuiweiArr.push(shuiItem);
            }
            shuiweiData.data = shuiweiArr;
          }
        }
  
        if (shuiweiData.data.length == 0) {
          shuiweiData.data = new Array(new Array(utils.formatTime(new Date()), 0));
        }
        var series = new Array(shuiweiData);
        console.log(series);
        if (chartInstance) {
          setOption(chartInstance, {
            series
          });
        }
      }).catch(function(e){
        console.log(e);
      });
    }
    console.log(beginTime, endTime)
  },

  initChart: function (series) {
    this.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setOption(chart, {
        series
      });
      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;
      chartInstance = chart;
      this.setData({
        isDisposed: false
      });
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      no : options.dceNo || '',
      deviceId : options.deviceId || 0,
      barnName: options.barnName || '',
      zoneName : options.zoneName || '',
      devName : options.devName || ''
    });
    this.ecComponent = this.selectComponent('#mychart-dom-line')
    this.loadInnerChart();
    this.loadLevel();

    app.setNavBar()
    const { skin } = app.globalData
    this.setData({
      skin
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  loadInnerChart : function() {
    let that = this;
    utils.promiseGet('/wx/device/waterchannel/getWaterData', {"deviceId" : this.data.deviceId}).then(function(res){
      let shuiweiData = {
        name : "水位",
        data: [],
        type: 'line',
        areaStyle: {}
      };
      if (res.code == 200 && res.data) {
        if (res.data.list.length > 0) {
          var shuiweiArr = [];
          for (var i = 0; i < res.data.list.length; i++) {
            var shuiItem = new Array(res.data.list[i].createTime, res.data.list[i].level);
            shuiweiArr.push(shuiItem);
          }
          shuiweiData.data = shuiweiArr;
        }
      }

      if (shuiweiData.data.length == 0) {
        shuiweiData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      var series = new Array(shuiweiData);
      console.log(series);
      that.initChart(series);
    }).catch(function(e){
      console.log(e);
    });
  },
  loadLevel : function(){
    let that = this;
    let getListParams = {
      "deviceId": that.data.deviceId,
      "page": 1,
      "pageSize": 3,
    };
    utils.promiseGet('/wx/device/waterchannel/getList', getListParams).then(res => {
      let list = [];
      if (res.code == 200) {
        let result = res.data;
        if (result.rows.length > 0) {
          for (let i = 0; i < result.rows.length; i++) {
            let itemRow = {
              "time" : result.rows[i].createTime,
              "value" : result.rows[i].level
            };
            list.push(itemRow);
          }
        }
      } else {
      }
      this.setData({
        dataLevelList: list,
      });
    }).catch(e => {
      console.log(e);
    });
  },
  toWateLevel() {
    let jumpUrl = '/pages/record/waterLevel?deviceId=' + this.data.deviceId +
      "&dceNo=" + this.data.no + 
      "&barnName=" + this.data.barnName +
      "&zoneName=" + this.data.zoneName + 
      "&devName=" + this.data.devName;
    wx.navigateTo({
      url: jumpUrl,
    })
  }
})